package com.gxa.sso.exception;

import com.gxa.sso.result.ResultUtils;
import com.gxa.sso.utils.JsonUtils;
import com.gxa.sso.utils.ResponseUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zxd on 2020/12/8
 **/
public class MyExceptionHandlerResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {


        String msg="";
        Integer code=null;


        //判断是否是预期异常
        if(exception instanceof CustomerException){

            // 向下转型
           CustomerException customerException = (CustomerException) exception;
           msg=customerException.getMessageCode().getMessage();
           code=customerException.getMessageCode().getCode();
        }else{
            exception.printStackTrace();
            msg="对不起，系统开小差了!";
            code=50000;
        }

        //向客户端作出反馈
        ResponseUtils.responseJson(response,JsonUtils.objectToJson(ResultUtils.buildFail(code, msg)));

        ModelAndView modelAndView=new ModelAndView();
        return modelAndView;
    }
}
